package yc.bluetooth.libvoice;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import androidx.annotation.NonNull;
import com.example.bluetoothlibrary.model.SearchDevice;

import yc.bluetooth.libvoice.service.VoiceService;
import yc.bluetooth.libvoice.util.ServerClientUtil;

/**
 * 作者：yeqianyun on 2020/2/12 15:52
 * 邮箱：1612706976@qq.com
 *
 *  VoiceService封装
 *
 *  绑定服务 / 解绑服务
 *  扫描设备 / 扫描结果
 *  连接设备
 *  语音数据接收-> 播放语音数据
 */
public class VoiceTool {

    private static final String TAG = VoiceTool.class.getSimpleName();

    private Context mContext;
    private Messenger serverMessenger;   //获取的服务器端的Messenger
    private Messenger clientMessenger;   //本客户端的Messenger
    private boolean isServiceBounded = false;
    private ServiceConnection serviceConnection;
    private VoiceToolListener listener;

    /**
     * 定义Handler
     * 接收来自服务端的消息、数据
     */
    @SuppressLint("HandlerLeak")
    private Handler clientHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {

            switch (msg.what) {
                case Cons.MSG_REPO_SCAN_DEVICE:  //扫描到设备
                    Log.d(TAG,"client receive from server scan device");
                    SearchDevice searchDevice = (SearchDevice) msg.obj;
                    if(listener != null){
                        listener.foundDevice(searchDevice.bluetoothDevice,searchDevice.rssi,searchDevice.scanRecord);
                    }
                    break;

                case Cons.MSG_REPO_SCAN_FINISHED:  //扫描结束
                    Log.d(TAG, "client receive from server scan finish");
                    if(listener != null){
                        listener.scanFinished();
                    }
                    break;

                case Cons.MSG_REPO_SCAN_OUT_TIME:  //扫描超时（扫描不到任何设备 ）
                    Log.e(TAG, "client receive from server scan out time!");
                    if(listener != null){
                        listener.scanOutTime();
                    }
                    break;

                case Cons.MSG_REPO_PAIR_CONNECT_STATE: //配对连接状态
                    boolean isConnected = (boolean) msg.obj;
                    Log.e(TAG, "client receive from server pair connect state = " + isConnected);
                    if(listener != null){
                        listener.pairConnectState(isConnected);
                    }
                    break;

                case Cons.MSG_REPO_UI_STRING_NOTIFY:  //通知界面
                    String info = (String) msg.obj;
                    int infoLevel = msg.arg1;
                    if(listener != null){
                        listener.onUiStringNotify(info,infoLevel);
                    }
                    break;

                case Cons.MSG_REPO_SUCCESS:  //接受语音数据、播报成功
                    if(listener != null){
                        listener.onSuccess();
                    }
                    break;

                case Cons.MSG_REPO_ERROR:  //出错
                    String errorInfo = (String) msg.obj;
                    if(listener != null){
                        listener.onError(errorInfo);
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    };

    public VoiceTool(Context mContext) {
        this.mContext = mContext;
        //初始化本客户端Messenger
        clientMessenger = new Messenger(clientHandler);

        //初始化变量
        initServiceConnection();
        //绑定服务
        doBind();
    }

    public void setListener(VoiceToolListener listener) {
        this.listener = listener;
    }

    /**
     * 扫描设备
     */
    public void scanDevice() {
        ServerClientUtil.sendToServerMsg(serverMessenger,clientMessenger,Cons.MSG_SCAN);
    }

    /**
     * 停止扫描
     */
    public void stopScanDevice() {
        ServerClientUtil.sendToServerMsg(serverMessenger,clientMessenger,Cons.MSG_STOP_SCAN);
    }

    /**
     * 配对连接设备
     */
    public void pairConnectDevice(BluetoothDevice bluetoothDevice){
        ServerClientUtil.sendToServerMsg(serverMessenger,clientMessenger,Cons.MSG_PAIR_CONNECT,bluetoothDevice);
    }

    /**
     * 断开连接、解除配对
     */
    public void disPairDisConnectDevice(){
        ServerClientUtil.sendToServerMsg(serverMessenger,clientMessenger,Cons.MSG_DIS_PAIR_DISCONNECT);
    }

    /**
     * 开始接收语音数据
     */
    public void startVoice(){
        //客户端向服务器端  开始升级
        ServerClientUtil.sendToServerMsg(serverMessenger,clientMessenger,Cons.MSG_START_VOICE);
    }

    /**
     * 关闭服务
     */
    public void closeService() {
        doUnbind();
        isServiceBounded = false;
        serverMessenger = null;
        serviceConnection = null;
    }

    private void doBind() {
        Log.d(TAG, "doBind():");
        Intent intent = new Intent(mContext, VoiceService.class);
        mContext.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void doUnbind(){
        Log.d(TAG,"doUnbind():");
        mContext.unbindService(serviceConnection);
    }

    private void initServiceConnection() {
        serviceConnection = new ServiceConnection() {
            //服务绑定时调用
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.d(TAG,"onServiceConnected(): name.getClassName() = " + name.getClassName());

                isServiceBounded = true;
                serverMessenger = new Messenger(service);
                //初始化蓝牙
                ServerClientUtil.sendToServerMsg(serverMessenger,clientMessenger,Cons.MSG_INIT_BLUETOOTH,Cons.BLE);

            }

            //服务异常解绑时调用，正常解绑不会调用。
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e(TAG,"onServiceDisconnected(): name.getClassName() = " + name.getClassName());
                isServiceBounded = false;
                serverMessenger = null;
            }
        };

    }



}
